package com.fzrskj.cloud.free.user.service.member;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.user.service.member.vo.MemberImportItemVo;
import com.fzrskj.cloud.free.user.utils.proin.ExcelReadUtils;
import com.fzrskj.cloud.free.user.utils.member.MemberImportUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.XmlCodeParser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * MemberImportService.
 *
 * @author zj.
 *         Created on 2019/5/8 0008.
 */
public class MemberImportService extends CObject {
    /**
     * 会员导入：文件上传.
     */
    public String memberImportUserUpload (HttpServletRequest req, HttpServletResponse rsp, String p, String sid) {
        List<MemberImportItemVo> memberList = new ArrayList<>();
        try {
            String[] keys = new String[20];
            keys[0] = "userName";
            keys[1] = "email";
            keys[2] = "balance";
            keys[3] = "openId";
            keys[4] = "loginType";
            keys[5] = "levelName";
            keys[6] = "password";
            keys[7] = "passwordMd5";
            keys[8] = "mobile";
            keys[9] = "registerTime";
            keys[10] = "registerIp";
            keys[11] = "fullName";
            keys[12] = "companyName";
            keys[13] = "certType";
            keys[14] = "provinceCode";
            keys[15] = "cityCode";
            keys[16] = "address";
            keys[17] = "isCertified";
            keys[18] = "certFile";
            keys[19] = "certCode";

            List<String> forceKeys = new ArrayList<>();
            forceKeys.add("mobile");

            //从excel中读取
            memberList = ExcelReadUtils.readXls(req, MemberImportItemVo.class, keys, 1, 1, forceKeys);

            //预先过滤
            MemberImportUtils importUtils = new MemberImportUtils();
            memberList = importUtils.refer(memberList);

        } catch (Exception e) {
            return XmlCodeParser.formatResultTips(false, "ERROR",
                    "读取csv失败，请检查导入内容。异常信息：" + e.getMessage());
        }
        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, JSONObject.toJSONString(memberList));
    }

    /**
     * 会员导入：保存.
     */
    public String memberImportUser (HttpServletRequest req, HttpServletResponse rsp, String p, String sid) {
        List<MemberImportItemVo> memberList = CJsonTool.getListValue(p, "members", new ArrayList<>(), MemberImportItemVo.class);
        if (memberList.isEmpty()) {
            return XmlCodeParser.formatResultTips(false, "ERROR", "无导入数据");
        }

        MemberImportUtils importUtils = new MemberImportUtils();
        memberList = importUtils.save(memberList);
        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, JSONObject.toJSONString(memberList));
    }
}
